package com.kongmou.springDataJpaAdvanced.service;

import com.kongmou.springDataJpaAdvanced.dao.impl.RoleRepository;
import com.kongmou.springDataJpaAdvanced.dao.impl.UserRepository;
import com.kongmou.springDataJpaAdvanced.dao.impl.UserRoleRepository;
import com.kongmou.springDataJpaAdvanced.domain.Role;
import com.kongmou.springDataJpaAdvanced.domain.User;
import com.kongmou.springDataJpaAdvanced.domain.UserRole;
import org.apache.shiro.crypto.RandomNumberGenerator;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;

@Service
public class UserServiceImpl {

    @Resource
    private UserRepository userRepository;

    @Resource
    private RoleRepository roleRepository;

    @Resource
    private UserRoleRepository userRoleRepository;

    private RandomNumberGenerator randomNumberGenerator =
            new SecureRandomNumberGenerator();
    /**
     * 保存用户
     * @param user
     * @return
     */
    public User save(User user, String roleId) {
       // User mUser = findByName(user.getName());
       // AssertUtils.isNull(mUser,"用户名已经存在!");
        if(StringUtils.isEmpty(user.getRegionName())){
            user.setRegion("86");
            user.setRegionName("中国");
        }
        //设置用户状态
        user.setStatus("1");
        //设置用户标签
        user.setType("user");
        String password = user.getPassword();
        //对密码进行加盐
        String salt = randomNumberGenerator.nextBytes().toHex();
        user.setSalt(salt);
        password = new Md5Hash(password, salt).toString();
        //添加创建时间
        user.setPassword(password);
        //生成日期对象
        Date current_date = new Date();
        //设置日期格式化样式为：yyyy-MM-dd
        SimpleDateFormat SimpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        //格式化当前日期
        SimpleDateFormat.format(current_date.getTime());
        user.setCreateTime(current_date);
        user = userRepository.save(user);
        //给用户分配隐藏角色 用于给用户直接分配角色
        Role role = new Role();
        role.setName(user.getId());
        role.setHide(true);
        role = roleRepository.save(role);
        user.setHideRoleId(role.getId());
        //保存用户关联关系
        userRoleRepository.save(new UserRole(user.getId(),role.getId()));
        //绑定角色——成都农委接入上报
        userRoleRepository.save(new UserRole(user.getId(),roleId));
        return user;
    }
}
